//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Clipbrd.hpp"
#include "uCalculatrice.h"
#include "EIC.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CEdit"
#pragma resource "*.dfm"

//---------------------------------------------------------------------------
__fastcall TfCalculatrice::TfCalculatrice(TComponent* Owner)
    : CForm(Owner)
{
    m_OnSetValue = NULL;
    if (!ComponentState.Contains(csDesigning)) {
        // on stocke la méthode actuelle de traitement des messages
        OldWndProc = eResult->WindowProc;
        // on affecte en propriété notre propre méthode
        eResult->WindowProc = MyWndProc;
    }    
}
//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::btnClick(TObject *Sender)
{
    bNewValue = true;
    Init();

    if (Sender == btn1)
      eResult->Text = eResult->Text + "1";
    else if (Sender == btn2)
      eResult->Text = eResult->Text + "2";
    else if (Sender == btn3)
      eResult->Text = eResult->Text + "3";
    else if (Sender == btn4)
      eResult->Text = eResult->Text + "4";
    else if (Sender == btn5)
      eResult->Text = eResult->Text + "5";
    else if (Sender == btn6)
      eResult->Text = eResult->Text + "6";
    else if (Sender == btn7)
      eResult->Text = eResult->Text + "7";
    else if (Sender == btn8)
      eResult->Text = eResult->Text + "8";
    else if (Sender == btn9)
      eResult->Text = eResult->Text + "9";
    else if (Sender == btn0) {
      if ( eResult->Text != "0")          eResult->Text = eResult->Text + "0";
    }
    else if (Sender == btnPoint) {
      if ( eResult->Text.Pos(",") == 0 )  eResult->Text = eResult->Text + ",";
    }
    else if (Sender == btnC) {
        asResultat = "0";
        asOldValue = "0";
        eResult->Text = "0";
    }
    ActiveControl = NULL;
}


//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::btnOperationClick(TObject *Sender)
{
    if (Sender == btnPourcent) {
        bPourcent = true;
    }
    if (bOperationEnCours && bNewValue) {
        Calc();
    }
    asOldValue = eResult->Text;
    bRemplaceVal = true;

    if (Sender == btnPlus)
        asOperateur = "+";
    else if (Sender == btnMoins)
        asOperateur = "-";
    else if (Sender == btnMultiplie)
        asOperateur = "*";
    else if (Sender == btnDiviser)
        asOperateur = "/";
    else if (Sender == btnPourcent) {
        asOperateur = "%";
    }

    bOperationEnCours = true;
    Init();
    eResult->Text = asOldValue;
    bRemplaceVal = true;
}

//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::btnEgaleClick(TObject *Sender)
{
    if (bOperationEnCours && bNewValue) {
        Calc();
    }
    eResult->Text = AnsiString(Round(asResultat.ToDouble(), 2));
    bRemplaceVal = false;
}

//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::Calc()
{
    if (asOperateur == "+") {
        if (!bPourcent)
            asResultat = AnsiString( asOldValue.ToDouble() + eResult->Text.ToDouble() );
        else
            asResultat = AnsiString( asOldValue.ToDouble() + (eResult->Text.ToDouble() * asOldValue.ToDouble())/100 );
    }
    if (asOperateur == "-") {
        if (asOldValue != "0") {
            if (!bPourcent)
                asResultat = AnsiString( asOldValue.ToDouble() - eResult->Text.ToDouble() );
            else
                asResultat = AnsiString( asOldValue.ToDouble() - (eResult->Text.ToDouble() * asOldValue.ToDouble())/100 );
        } else
            asResultat = eResult->Text;
    }
    if (asOperateur == "*") {
        if (!bPourcent)
            asResultat = AnsiString( asOldValue.ToDouble() * eResult->Text.ToDouble() );
        else
            asResultat = AnsiString( asOldValue.ToDouble() * eResult->Text.ToDouble() /100 );
    }
    if (asOperateur == "/") {
        if ( eResult->Text != "0") {
            if (!bPourcent)
                asResultat = AnsiString( asOldValue.ToDouble() / eResult->Text.ToDouble() );
            else
                asResultat = AnsiString( asOldValue.ToDouble() / eResult->Text.ToDouble() /100 );
        } else {
             asResultat = "0";
        }
    }

    eResult->Text = AnsiString(Round(asResultat.ToDouble(), 2));//Arrondi(asResultat);
    bRemplaceVal = true;
    bNewValue = false;
    bPourcent = false;
    bOperationEnCours = false;
}

//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::Init()
{
    if (eResult->Text == "0" || bRemplaceVal ) {
        eResult->Text = EmptyStr;
        bRemplaceVal = false;
    }
}

//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::btnCKeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
    if (Key == VK_RETURN) {
        btnOKClick(Sender);
    }
    if (Key == 8)  {                  // suppr
        btnRetour->Click();
    }
    if (Key == 27) {                  // echap
        ModalResult = mrCancel;
        FormDeactivate(Sender);
    }
    if (Key == 46) {                  // retour arrière
        btnRetour->Click();
    }
    if (Key == 96)  {                 // 0
        btn0->Click();
    }
    if (Key == 97)  {                 // 1
        btn1->Click();
    }
    if (Key == 98)  {                 // 2
        btn2->Click();
    }
    if (Key == 99)  {                 // 3
        btn3->Click();
    }
    if (Key == 100)  {                 // 4
        btn4->Click();
    }
    if (Key == 101)  {                 // 5
        btn5->Click();
    }
    if (Key == 102)  {                 // 6
        btn6->Click();
    }
    if (Key == 103)  {                 // 7
        btn7->Click();
    }
    if (Key == 104)  {                 // 8
        btn8->Click();
    }
    if (Key == 105)  {                 // 9
        btn9->Click();
    }
    if (Key == 110)  {                 // ,
        btnPoint->Click();
    }
    if (Key == 187)  {                 // signe =
        btnEgale->Click();
    }
    if (Key == 107)  {                 // signe +
        btnPlus->Click();
    }
    if (Key == 109)  {                 // signe -
        btnMoins->Click();
    }
    if (Key == 106)  {                 // signe *
        btnMultiplie->Click();
    }
    if (Key == 111)  {                 //  signe /
        btnDiviser->Click();
    }
    if (Key == 67 &&  !Shift.Contains(ssCtrl))  {  // touche C -> Clear
        btnC->Click();
    }
    if (Key == 192 && Shift.Contains(ssShift))  {  // touche %
        btnPourcent->Click();
    }
    if (Key == 67 && Shift.Contains(ssCtrl))  {  // CTRL + C
        SendMessage(eResult->Handle,WM_COPY,0,0);
    }
    if (Key == 86 && Shift.Contains(ssCtrl))  {  // CTRL + V
        SendMessage(eResult->Handle,WM_PASTE,0,0);
    }
 }

//---------------------------------------------------------------------------
AnsiString __fastcall TfCalculatrice::Arrondi(AnsiString asValue)
{
    int nPosVirgule = asValue.Pos(",");
    if (nPosVirgule != 0) {
        // ne garder que 4 chiffres après la virgule
        if (nPosVirgule < asValue.Length()-4) {
            asValue = asValue.SubString(1, nPosVirgule + 4);
        }
    }
    return asValue;
}

//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::MyWndProc(Messages::TMessage &Message)
{
    switch (Message.Msg) {
        case WM_COPY : {
                    // récupération du contenu du presse-papier
                    Clipboard()->AsText = eResult->Text;
                    break;
        }
        case WM_PASTE : {
                    // récupération du contenu du presse-papier
                    AnsiString txt = Clipboard()->AsText;
                    if (txt.ToIntDef(0) != 0)
                        eResult->Text = StringReplace(txt, "\r\n", "", TReplaceFlags() << rfReplaceAll);
                    break;
        }
        default : {
                    // traitement de tout autre message avec la méthode "par défaut"
                    OldWndProc(Message);
        }
    }
}

//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::btnOKClick(TObject *Sender)
{
    ModalResult = mrOk;
    if (bOperationEnCours && bNewValue) {
        Calc();
    }
    FormDeactivate(Sender);
}

//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::FormDeactivate(TObject *Sender)
{
    Close();
}

//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::AfficherCalc (TControl *CtrlAppelant, const AnsiString &asValue, TOnSetValue OnSetValue)
{
    ASSERT(CtrlAppelant && CtrlAppelant->Parent);

    // Place la fenêtre au bonne endroit
    TPoint point;
    point.x = CtrlAppelant->Left;
    point.y = CtrlAppelant->Top + CtrlAppelant->Height;
    point   = CtrlAppelant->Parent->ClientToScreen(point);
    Left = point.x;
    Top  = point.y;

    m_OnSetValue = OnSetValue;
    bRemplaceVal = true;

    Show();
    eResult->Text = asValue;

}

//------------------------------------------------------------------------------
void __fastcall TfCalculatrice::FormClose(TObject *Sender,
      TCloseAction &Action)
{
    if (m_OnSetValue && ModalResult == mrOk)
        m_OnSetValue(AnsiString(lArrond(eResult->Text.ToDouble())));
}
//---------------------------------------------------------------------------

void __fastcall TfCalculatrice::FormShow(TObject *Sender)
{
    asResultat = eResult->Text;
    asOldValue = "0";
    Init();
    bRemplaceVal = true;
}
//---------------------------------------------------------------------------
void __fastcall TfCalculatrice::btnPlusMoinsClick(TObject *Sender)
{
    if (eResult->Text.ToIntDef(0) != 0) {
        if (eResult->Text.Pos("-") == 0)
            eResult->Text = eResult->Text.Insert("-", 1);
        else
            eResult->Text = eResult->Text.Delete(1, 1);
    }
    ActiveControl = NULL;
}
//---------------------------------------------------------------------------

void __fastcall TfCalculatrice::btnRetourClick(TObject *Sender)
{
    if (     (eResult->Text.Pos("-") == 0  && eResult->Text.Length() == 0 )
          || (eResult->Text.Pos("-") != 0  && eResult->Text.Length() == 2 ) )
        eResult->Text = "0";
    else {
        eResult->Text = eResult->Text.Delete(eResult->Text.Length(),1);
        if (eResult->Text.IsEmpty()) eResult->Text = "0";
    }
    ActiveControl = NULL;
}
//---------------------------------------------------------------------------

